package org.jeecg.modules.complain.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.AliyunOssHelper;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.*;
import org.jeecg.common.util.sms.SmsUtil;
import org.jeecg.modules.complain.entity.*;
import org.jeecg.modules.complain.service.IRepairChargeService;
import org.jeecg.modules.complain.service.IRepairConfigService;
import org.jeecg.modules.complain.service.IRepairService;
import org.jeecg.modules.complain.service.IRepairStatusService;
import org.jeecg.modules.message.entity.SysMessage;
import org.jeecg.modules.message.service.ISysMessageService;
import org.jeecg.modules.system.entity.SmsEntity;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
* @Description: 报修处理
* @Author: jeecg-boot
* @Date:   2019-07-29
* @Version: V1.0
*/
@Slf4j
@Api(tags="报修处理")
@RestController
@RequestMapping("/b/repair")
/*@RequiresRoles("test001")*/
@CrossOrigin(origins = "*",allowCredentials="true",allowedHeaders = "",methods = {})
public class RepairController {
   @Autowired
   private IRepairService repairService;
   @Autowired
   private IRepairConfigService repairConfigService;
   @Autowired
   private IRepairStatusService repairStatusService;
   @Autowired
   private IRepairChargeService repairChargeService;
   @Autowired
   private ISysMessageService sysMessageService;
   @Autowired
   private ISysUserRoleService sysUserRoleService;
   private static String  templateCode ="SMS_142951838";
   private static long seq = 0;
   /**
     * 分页列表查询
    * @param repair
    * @param pageNo
    * @param pageSize
    * @param req
    * @return
    */
   @AutoLog(value = "报修处理-分页列表查询")
   @ApiOperation(value = "报修处理-分页列表查询", notes = "报修处理-分页列表查询")
   @GetMapping(value = "/list")
   public Result<IPage<Repair>> queryPageList(Repair repair,
                                              String startTime, String endTime,
                                              @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                              @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) throws ParseException {
       int key = 0;
       Result<IPage<Repair>> result = new Result<IPage<Repair>>();
       if (repair.getStatus() != null) {
           key = repair.getStatus();
           if (key == 2000) {
               repair.setStatus(null);
           }
       }
       if (repair.getUserName()!=null){
           repair.setUserName("*"+repair.getUserName()+"*");
       }
       if (repair.getNo()!=null){
           repair.setNo("*"+repair.getNo()+"*");
       }
       //权限处理
       List<String> projectIds = sysUserRoleService.queryProjectIds(repair);
       repair.resetValue();//置空防止自动查询(非表中字段)
       QueryWrapper<Repair> queryWrapper = QueryGenerator.initQueryWrapper(repair, req.getParameterMap());
        if (key == 2000) {
           Calendar date = Calendar.getInstance();
           queryWrapper.lt("bespeak_from_time", date.getTime());
           queryWrapper.ne("status",CommonDefine.REPAIR_STATUS_900);
           queryWrapper.ne("status",CommonDefine.REPAIR_STATUS_600);
           queryWrapper.ne("status",CommonDefine.REPAIR_STATUS_800);
       }
        queryWrapper.eq("del_flag", 0);
        if (startTime!=null){
            queryWrapper.gt("repair_date",startTime);
        }
        if (endTime!=null){
            queryWrapper.lt("repair_date",endTime);
        }
        if (projectIds.size() <=0){
            queryWrapper.eq("project_id","");
        }else{
            queryWrapper.in("project_id",projectIds);
        }
        Page<Repair> page = new Page<Repair>(pageNo, pageSize);
        IPage<Repair> pageList = repairService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
   }

   /**
     *  pc添加Repair 包括受理和指派
    * @param repair
    * @return
    */

   @PostMapping(value = "/add")
   public Result<Repair> add(@RequestBody Repair repair){
       Result<Repair> result = new Result<Repair>();
       //依据项目拿到报修流程配置
       String projectId = repair.getProjectId();
       if (StringUtils.isEmpty(projectId)){
           return Result.error("请选择具体项目");
       }
       if (repair.getAttachFile()!=null){
           repair.setAttachFile(repair.getAttachFile().substring(0,repair.getAttachFile().length()-1));
       }
       String departId = repairConfigService.getDepartIdByProjectId(projectId);
       if (StringUtils.isEmpty(departId)){
           return Result.error("系统错误,联系管理员");
       }
       RepairConfig repairConfig = repairService.selectConfigByDepartId(departId);
       if ( null == repairConfig ){
           return Result.error("该项目管理处没有开通报修功能");
       }
       repair.setDepartId(departId);
       if (!StringUtils.isEmpty(repair.getRoomId())){
           BaseCustomer baseCustomer = repairService.selectByRoomId(repair.getRoomId());
           if (baseCustomer != null){
           repair.setCustomerId(baseCustomer.getId());
           repair.setCustomerName(baseCustomer.getName());
           repair.setCustomerPhone(baseCustomer.getTelphone());
           }
       }
       String floorId = repairService.selectFloor(repair.getRoomId());
       repair.setFloorId(floorId);
       //生成报修单号
       String repairNo = DateUtils.getDate("yyyyMMddHHmmss") + String.format("%06d", seq++);
       if(seq > 999999){
           seq = 0;
       }
       repair.setNo(repairNo);
       repair.setCreateTime(new Date());
       repair.setRepairWay(CommonDefine.Repair.REPAIR_TYPE_1);
       repair.setConfigId(repairConfig.getId());
       repair.setUpdateTime(new Date());
       String repairid = null;
       //判断流程配置条件进行分配 新平台只做抢单和不抢单判断
       if (repairConfig.getRepairModel() == 0){ //普通模式 直接支配维修工维修
         repair.setStatus(CommonDefine.REPAIR_STATUS_100);//待处理状态
         repairService.save(repair);
         repairid = repair.getId();
       }else {
           return  result.error500("暂不支持抢单模式，请更换配置");
       }
       if (null != repair.getHandId() && repair.getHandId() != ""){
           RepairStatus repairStatus = new RepairStatus();
           repairStatus.setCreateTime(new Date());
           repairStatus.setRepairId(repairid);
           repairStatus.setUserName(repair.getHandName());
           repairStatus.setUserId(repair.getHandId());
           repairStatus.setCreateBy(SsoUtil.getLoginUser().getRealname());
           String phone = SsoUtil.getLoginUser().getPhone();

           String userName = repair.getUserName();
           Integer integer = repairService.updateRepairStatus(repairStatus.getRepairId(),CommonDefine.REPAIR_STATUS_200);
           //存入维修状态表 报修受理状态
           repairStatus.setStatus(CommonDefine.REPAIR_STATUS_200);
           SysUser sysUser = repairService.selectByUserId(repair.getHandId());
           repairStatus.setMobile(sysUser.getPhone());
           SmsEntity smsEntity = SmsUtil.sendSms(sysUser.getPhone(), templateCode, "community", repair.getProjectName(), "username", userName, "number", repair.getMobile());
           String status = "";
           if (smsEntity.getMessage().equalsIgnoreCase("OK")){
               status = "1";
           }else {
               status = "2";
           }
           saveMessage(smsEntity.getContent(),repair.getProjectId(),repair.getDepartId(),sysUser.getPhone(),status);
           boolean falg = repairStatusService.save(repairStatus);
           if (falg && integer>0){
               return Result.ok("受理并指派成功");
            }
           }else{
           RepairStatus rs=new RepairStatus();
           rs.setStatus(CommonDefine.REPAIR_STATUS_100);
           rs.setCreateTime(new Date());
           rs.setRepairId(repairid);
           boolean save = repairStatusService.save(rs);
           result.setSuccess(save);
       }
       return result;
   }



   /**
     *   通过id删除
    * @param id
    * @return
    */
   @AutoLog(value = "报修处理-通过id删除")
   @ApiOperation(value="报修处理-通过id删除", notes="报修处理-通过id删除")
   @DeleteMapping(value = "/delete")
   public Result<?> delete(@RequestParam(name="id",required=true) String id) {
       try {
           repairService.removeById(id);
       } catch (Exception e) {
           log.error("删除失败",e.getMessage());
           return Result.error("删除失败!");
       }
       return Result.ok("删除成功!");
   }

   /**
     *  批量删除
    * @param ids
    * @return
    */
   @AutoLog(value = "报修处理-批量删除")
   @ApiOperation(value="报修处理-批量删除", notes="报修处理-批量删除")
   @DeleteMapping(value = "/deleteBatch")
   public Result<Repair> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
       Result<Repair> result = new Result<Repair>();
       if(ids==null || "".equals(ids.trim())) {
           result.error500("参数不识别！");
       }else {
           this.repairService.removeByIds(Arrays.asList(ids.split(",")));
           result.success("删除成功!");
       }
       return result;
   }
   /**
     * 通过id查询
    * @param id
    * @return
    */
   @AutoLog(value = "报修处理-通过id查询")
   @ApiOperation(value="报修处理-通过id查询", notes="报修处理-通过id查询")
   @GetMapping(value = "/queryById")
   public Result<Repair> queryById(@RequestParam(name="id",required=true) String id) {
       Result<Repair> result = new Result<Repair>();
       Repair repair = repairService.getById(id);
       if(repair==null) {
           result.error500("未找到对应实体");
       }else {
           result.setResult(repair);
           result.setSuccess(true);
       }
       return result;
   }

 /**
     * 导出excel
  *
  * @param request
  * @param response
  */
 @RequestMapping(value = "/exportXls")
 public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
     // Step.1 组装查询条件
     QueryWrapper<Repair> queryWrapper = null;
     Repair repair = new Repair();
     try {
         String paramsStr = request.getParameter("paramsStr");
         if (oConvertUtils.isNotEmpty(paramsStr)) {
             String deString = URLDecoder.decode(paramsStr, "UTF-8");
            repair = JSON.parseObject(deString, Repair.class);
             queryWrapper = QueryGenerator.initQueryWrapper(repair, request.getParameterMap());
         }
     } catch (UnsupportedEncodingException e) {
         e.printStackTrace();
     }

     //Step.2 AutoPoi 导出Excel
     ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
     //List<Repair> pageList = repairService.list(queryWrapper);
     List<Repair> pageList = repairService.selectRepairExport(repair);
     for (Repair vo : pageList) {
         if (vo.getRepairWay().equals(0)){
             vo.setRepairWay("线上");
         }else {
             vo.setRepairWay("线下");
         }
         if (vo.getRepairArea().equals("0")){
             vo.setAreaName("公共区域");
         }else {
             vo.setAreaName("个人区域");
         }
         if (vo.getStatus()==CommonDefine.REPAIR_STATUS_100){
             vo.setRepairStatusName("待受理");
         }else if (vo.getStatus()==CommonDefine.REPAIR_STATUS_200){
             vo.setRepairStatusName("待维修");
         }else if (vo.getStatus()==CommonDefine.REPAIR_STATUS_300){
             vo.setRepairStatusName("维修中");
         }else if (vo.getStatus()==CommonDefine.REPAIR_STATUS_600){
             vo.setRepairStatusName("已完成");
         }else if (vo.getStatus()==CommonDefine.REPAIR_STATUS_900){
             vo.setRepairStatusName("已评价");
         }else if (vo.getStatus()==CommonDefine.REPAIR_STATUS_800){
             vo.setRepairStatusName("已取消");

         }	  }

     //导出文件名称
     mv.addObject(NormalExcelConstants.FILE_NAME, "报修处理列表");
     mv.addObject(NormalExcelConstants.CLASS, Repair.class);
     mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("报修处理列表数据", "导出人:Jeecg", "导出信息"));
     mv.addObject(NormalExcelConstants.DATA_LIST, pageList);

     return mv;
 }

 /**
     * 通过excel导入数据
  *
  * @param request
  * @param response
  * @return
  */
 @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
 public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
     MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
     Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
     for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
         MultipartFile file = entity.getValue();// 获取上传文件对象
         ImportParams params = new ImportParams();
         params.setTitleRows(2);
         params.setHeadRows(1);
         params.setNeedSave(true);
         try {
             List<Repair> listRepairs = ExcelImportUtil.importExcel(file.getInputStream(), Repair.class, params);
             repairService.saveBatch(listRepairs);
             return Result.ok("文件导入成功！数据行数:" + listRepairs.size());
         } catch (Exception e) {
             log.error(e.getMessage(),e);
             return Result.error("文件导入失败:"+e.getMessage());
         } finally {
             try {
                 file.getInputStream().close();
             } catch (IOException e) {
                 e.printStackTrace();
             }
         }
     }
     return Result.ok("文件导入失败！");
 }
    /**
     * 报修详情
     * @param: id
     * table:repair
     */
   @RequestMapping("getRepairDetail")
    public Result<Object> getRepairDetail(@RequestParam(name = "id")String id,
                                          @RequestParam(name = "status")String status) throws ParseException {
      Result<Object> result = new Result<>();
       if (StringUtils.isEmpty(id)){
           return Result.error("请选择具体的报修单");
       }
       Date startTime = new Date();
       Date endTime = new Date();
        Repair repair = repairService.selectById(id,status);
        List<RepairStatus> repairStatuses = repairStatusService.selectRepairStatus(id);
       for (RepairStatus repairStatus: repairStatuses) {
           if (repairStatus.getStatus()==300){
                 startTime = repairStatus.getCreateTime();
           }if (repairStatus.getStatus()==600){
                 endTime = repairStatus.getCreateTime();
           }
       }
       if (startTime != null && endTime !=null){
           long diff = endTime.getTime() - startTime.getTime();
           long days = diff / (1000 * 60 * 60 * 24);
           long hours = (diff-days*(1000 * 60 * 60 * 24))/(1000* 60 * 60);
           long minutes = (diff-days*(1000 * 60 * 60 * 24)-hours*(1000* 60 * 60))/(1000* 60);
           long s = (diff / 1000 - days * 24 * 60 * 60 - hours * 60 * 60 - minutes * 60);

           repair.setRepairWorkTime(""+days+"天"+hours+"小时"+minutes+"分"+s+"秒");

       }
        HashMap<String, Object> map = new HashMap<>();
        map.put("repair",repair);
        map.put("repairStatuses",repairStatuses);
        result.setResult(map);
        return  result;
   }
    /**
     * 报修受理
     * @param ：
     */
    @RequestMapping("repairHandle")
    public  Result  repairHandle( RepairStatus repairStatus){

        //缺少通知 接单后接口返回状态
        Result<Object> result = new Result<>();
        LoginUser loginUser = SsoUtil.getLoginUser();
        repairStatus.setCreateBy(loginUser.getRealname());
        if (StringUtils.isEmpty(repairStatus.getRepairId())){
            return  Result.error("请选择报修单");
        }
        if (repairStatus.getUserId() == null || repairStatus.getMobile() ==null || repairStatus.getUserName()==null){
            return  Result.error("请选择维修人员");
        }
        RepairStatus repair = repairStatusService.selectByRepairId(repairStatus.getRepairId(),CommonDefine.REPAIR_STATUS_200);
        if (repair != null){
            return Result.error("该维修单已经指派给维修人员");
        }
        SysUser sysUser = repairService.selectByUserId(repairStatus.getUserId());
        repairStatus.setMobile(sysUser.getPhone());
        //逻辑删除受理状态
        repairStatusService.delete(repairStatus.getRepairId(),CommonDefine.REPAIR_STATUS_100);
        //报修受理，状态改为200
        Integer integer = repairService.updateRepairStatus(repairStatus.getRepairId(),CommonDefine.REPAIR_STATUS_200);
        //存入维修状态表 报修受理状态
        repairStatus.setStatus(CommonDefine.REPAIR_STATUS_200);
        boolean falg = repairStatusService.save(repairStatus);
        //推送
        Repair repair1 = repairService.selectByIds(repairStatus.getRepairId());
        String projectName = repairService.selectProjectName(repair1.getProjectId());
        SmsEntity smsEntity = SmsUtil.sendSms(repairStatus.getMobile(), templateCode, "community",projectName, "username", repair1.getUserName(), "number", repair1.getMobile());
        String status = "";
        if (smsEntity.getMessage().equalsIgnoreCase("OK")){
            status = "1";
        }else {
            status = "2";
        }
        saveMessage(smsEntity.getContent(),repair1.getProjectId(),repair1.getDepartId(),repairStatus.getMobile(),status);
        if (falg && integer>0){
            return Result.ok("受理成功");
        }
        return  result;
    }
    /**
     * 改派(依据报修单拿当前维修工)
     * @param  repairId
     */
    @RequestMapping("reassignment")
    public Result<RepairStatus> reassignment(@RequestParam(name = "repairId")String repairId,
                                             @RequestParam(name = "status")Integer status){
        Result<RepairStatus> result = new Result<>();
        RepairStatus repairStatus = repairStatusService.selectByRepairId(repairId,status);
        result.setResult(repairStatus);
        return  result;
    }
    /**
     * 更换维修人员
     */
    @RequestMapping("changePositionUser")
    public Result<Object> changePositionUser(RepairStatus repairStatus){
        Result<Object> result = new Result<>();
        if (StringUtils.isEmpty(repairStatus.getRepairId())){
            return Result.error("请选择需要改派的维修单");
        }
        if (StringUtils.isEmpty(repairStatus.getUserId())){
            return Result.error("请选择改派的人员");
        }
        boolean flag = false;
        repairStatus.setCreateTime(new Date());
        if (repairStatus.getStatus() == CommonDefine.REPAIR_STATUS_200){
            repairStatusService.delete(repairStatus.getRepairId(),repairStatus.getStatus());
            flag = repairStatusService.save(repairStatus);
        }else{
            repairStatusService.delete(repairStatus.getRepairId(),repairStatus.getStatus());
             //将维修单改为待处理状态
           repairStatus.setStatus(CommonDefine.REPAIR_STATUS_200);
           repairStatusService.save(repairStatus);
           Integer integer = repairService.updateRepairStatus(repairStatus.getRepairId(), CommonDefine.REPAIR_STATUS_200);
           flag = integer > 0;
        }
        if (flag){
            return  Result.ok("该维修单已成功改派");
        }
        return  result;
    }
    /**
     * 报修完成
     * @Param repairId
     *
     */
    @RequestMapping("repairComplete")
    public  Result<Object> repairComplete(RepairCharge repairCharge){
        Result<Object> result = new Result<>();
        String repairNo = DateUtils.getDate("yyyyMMddHHmmss") + String.format("%06d", seq++);
        if(seq > 999999){
            seq = 0;
        }
        if (StringUtils.isEmpty(repairCharge.getRepairId())){
             return Result.error("请选择报修单");
        }
         RepairStatus repairStatus = repairStatusService.selectByRepairId(repairCharge.getRepairId(),CommonDefine.REPAIR_STATUS_300);
         if ( null == repairStatus ){
             return  Result.error("该报修单还没有开始维修");
         }
        if (repairCharge.getRepairManHourfee()==null){
            return  Result.error("请填写工时费");
        }

        repairChargeService.save(repairCharge);
        repairStatusService.delete(repairCharge.getRepairId(),CommonDefine.REPAIR_STATUS_300);
        repairStatus.setContents(repairCharge.getRemarks());
        repairStatus.setCreateTime(new Date());
        repairStatus.setId(null);
        repairCharge.setRepairNo(repairNo);
        repairStatus.setStatus(CommonDefine.REPAIR_STATUS_600);
        repairStatus.setAttachFile(repairCharge.getAttachFile());
        repairStatus.setConfirmPay(1);
        repairStatusService.save(repairStatus);
        Integer integer = repairService.updateRepairStatus(repairCharge.getRepairId(), CommonDefine.REPAIR_STATUS_600);
        if (integer>0){
            return Result.ok("报修单完成");
        }
        return Result.error("系统故障,请联系管理员");
    }
    /**
     * 报修单取消
     * @Param repairId
     */
    @RequestMapping("cancleRepair")
    public Result<Object> cancleRepair(@RequestParam(name = "repairId")String repairId,
                                       @RequestParam(name = "remarks") String remarks){
        //缺少通知
        RepairStatus repairStatus = repairStatusService.selectByRepairId(repairId,CommonDefine.REPAIR_STATUS_200);
        if (repairStatus == null ){
            return Result.error("该报修单不可取消");
        }
        repairStatusService.delete(repairId,CommonDefine.REPAIR_STATUS_200);
        repairStatus.setStatus(CommonDefine.REPAIR_STATUS_800);
        repairStatus.setCreateTime(new Date());
        repairStatus.setContents(remarks);
        repairStatus.setId(null);
        repairStatusService.save(repairStatus);
        Integer integer = repairService.updateRepairStatus(repairId, CommonDefine.REPAIR_STATUS_800);
        if (integer > 0){
             return  Result.ok("报修单取消成功");
       }
        return  Result.error("系统故障,请联系管理员");
    }

    /**
     * 依据状态拿到所有的报修单
     * @param status
     */
    @RequestMapping("getRepairByStatus")
    public Result<List<Repair>>  getRepairByStatus(@RequestParam(name = "status")String status){
        Result<List<Repair>> repairListResult = new Result<>();
        List<Repair> repairs = repairService.selectByStatus(status);
        if(repairs == null ){
            return  Result.ok("该状态下没有报修单");
        }else {
            repairListResult.setResult(repairs);
        }
        return  repairListResult;
    }

    /**
     * 拿单条报修单数据
     * @Param repairId
     */
    @RequestMapping("getRepairdPrint")
    public Result<Repair> getRepairdPrint(@RequestParam(name = "departId")String departId,
                                          @RequestParam(name = "status")String status){
        Result<Repair> result = new Result<>();
        Repair repair = repairService.selectById(departId,status);
        result.setResult(repair);
        return result;
    }
    /**
     * 回访
     */
   @RequestMapping("returnService")
    public Result<Object> completeEvaluate(RepairStatus repairStatus){
       Result<Object> result = new Result<>();
       if (repairStatus.getReviewContent()==null){
           return  Result.error("请填写回访情况");
       }
       if (repairStatus.getReviewTime() == null ){
           return  Result.error("请填写回访日期");
       }
       repairStatus.setStatus(CommonDefine.REPAIR_STATUS_600);
       RepairStatus repairStatus1 = repairStatusService.selectByRepairId(repairStatus.getRepairId(), CommonDefine.REPAIR_STATUS_600);
       repairStatus1.setReviewTime(repairStatus.getReviewTime());
       repairStatus1.setReviewContent(repairStatus.getReviewContent());
       repairStatus1.setStatus(CommonDefine.REPAIR_STATUS_900);
       repairStatus1.setId(null);
       String commentImg = repairStatus.getCommentImg();
       if (StringUtils.isNotEmpty(commentImg)){
           commentImg = commentImg.substring(0, commentImg.length() - 1);
       }
       repairStatus1.setCommentImg(commentImg);
       repairStatusService.delete(repairStatus1.getRepairId(),CommonDefine.REPAIR_STATUS_600);
       repairStatusService.save(repairStatus1);
       Integer integer1 = repairService.updateRepairStatus(repairStatus1.getRepairId(), CommonDefine.REPAIR_STATUS_900);
       if ( integer1 >0){
           return  Result.ok("登记成功");
         }
       return result;
   }


    @RequestMapping("uploadFile")
    public Result<String> uploadImageNew(HttpServletRequest request, MultipartFile[] file) throws IOException {
        Result<String> result = new Result<>();
        String imageStr = "";
        for (MultipartFile s : file){
            // 上传图片的原始名称
            String originalFilename = s.getOriginalFilename();
            String key = "pic/";
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String ymd = sdf.format(new Date());
            // 新的图片名称(真实名称)
            String newFileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
            // 新图片的路径
            key += ymd + "/" + newFileName;
            Boolean pic_flg = AliyunOssHelper.put(key, s.getInputStream());
            if (pic_flg) {
                imageStr = imageStr + AliyunOssHelper.getUrlPath(key) + ";";
            } else {
                result.setMessage("出错了");
                return result;
            }
        }
        result.setResult(imageStr);
        result.setMessage(imageStr);
        return result;
    }
    @Configuration
    public class CorsConfig {
        private CorsConfiguration buildConfig() {
            CorsConfiguration corsConfiguration = new CorsConfiguration();
            // * 表示对所有的地址都可以访问
            corsConfiguration.addAllowedOrigin("*");
            //  跨域的请求头
            corsConfiguration.addAllowedHeader("*"); // 2
            //  跨域的请求方法
            corsConfiguration.addAllowedMethod("*"); // 3
            //加上了这一句，大致意思是可以携带 cookie
            //最终的结果是可以 在跨域请求的时候获取同一个 session
            corsConfiguration.setAllowCredentials(true);
            return corsConfiguration;
        }
        @Bean
        public CorsFilter corsFilter() {
            UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            //配置 可以访问的地址
            source.registerCorsConfiguration("/**", buildConfig()); // 4
            return new CorsFilter(source);
        }
    }
    private void saveMessage(String content,String projectId,String depatrId,String phone,String status){
        SysMessage sysMessage = new SysMessage();
        sysMessage.setEsType("1");
        sysMessage.setEsContent(content);
        sysMessage.setProjectId(projectId);
        sysMessage.setDepartId(depatrId);
        sysMessage.setEsReceiver(phone);
        sysMessage.setEsTitle("报修短信");
        sysMessage.setEsSendStatus(status);
        sysMessage.setEsSendTime(new Date());
        sysMessageService.save(sysMessage);
    }


}
